//index.js
//获取应用实例
var app = getApp()
Page({
	data: {
		root:'',
		siteroot:app.setting.siteroot,
		att_url:app.setting.att_url,
		action:'store.goodslist',
		showtype:0,
		loading:true,
		pagetitle:'小店下单',
		
	},
	onReady: function (){
	},
	onPullDownRefresh: function (){
		var the=this;
		var opt={};
		the.onLoad(opt);
		setTimeout(function(){
			wx.stopPullDownRefresh()
		},1000);
	},
	onLoad: function (opt){
		var the=this;
		wx.setNavigationBarTitle({'title':the.data.pagetitle});
		var route=the.route;
		the.setData({
			route:route,
		});
		if(opt && opt.isgoshare){
			the.setData({
					ShowGoshare:true,
			});
		}
		if(route){
			var path=route.slice(0,-6).split('/');
			app.access.plugin=path.shift();
			app.access.action=path.join('.');
		}
		if(opt){
			app.access.query =app.util.made_query(opt,true);
			app.access.op=opt.op?opt.op:'';
		}
	},
	onShow: function (){
		var the=this;
		console.log('route');console.log(the.route);
		setTimeout(()=>{
			the.getpagedata();
		},100);
	},
	getpagedata: function (){
		var the=this;
		if(app.access.plugin!='jy_weishop' || app.access.action!='store.goodslist'){
			return false;
		}
		app.util.get(app.access,function(res){
			console.log('app.access');console.log(app.access);
			//console.log('goodslist');console.log(res);
			res.selected = 0
			res.oldlist=[]
			if(res.category && res.category[0] && res.category[0].id){
				res.params.pcate=res.category[0].id;
			}
			the.setData({
				pagedata:res,
				pluginnav:app.session.menus,
				action:app.access.plugin+'/'+app.access.action+'/',
			});
			setTimeout(()=>{the.get_list(1);},200);
			the.refresh(res.totalprice);
		});
	},
	gohome: function() {
        app.util['access'](app.plugin_name+'/index/');
    },
	onPageScroll:function (e) { // 获取滚动条当前位置
		var showtopheader=this.data.showtopheader
	  if (e.scrollTop > 160 && !showtopheader) {
        this.setData({
          showtopheader: true
        })
      }
	  if(e.scrollTop < 30 && showtopheader){
		this.setData({
          showtopheader: false
        })  
	  }
	},
	// 搜索框文本内容的显示
	keyword: function (e) {
		var the = this
		the.setData({
		  'pagedata.params.keyword': e.detail.value
		})
	},
	//翻页
	onReachBottom: function () {
		var the=this;
		var isnodata=the.data.isnodata
		var loading=the.data.loading
		console.log('onReachBottom');
		if(!loading){
			console.log('get_list');
			the.get_list()
		}
	},
	get_list:function(e){
		var the=this;
		var pagedata=the.data.pagedata
		var isnodata = the.data.isnodata
		the.setData({
				loading:true
		});
		if(e){
			if(e.currentTarget){
				var data=e.currentTarget.dataset;
				if(data.type=='price'){
					pagedata.params.order='price';
					pagedata.params.order_type=pagedata.params.order_type==1?2:1;
				}
				if(data.type){
					pagedata.params.type=data.type;
					pagedata.params.order=data.type;
				}
				if(data.pcate){
					pagedata.params.pcate=data.pcate;
				}
			}		
			pagedata.params.page = 1;
			pagedata.goodslist=[];
			pagedata.list=[];
			isnodata=false;
		}else{
			if(isnodata){
				the.setData({
					loading:false
				});
				return false;
			}
		}
		
		var query=app.util.made_query(pagedata.params);
		if(pagedata.showlist=='pingjia'){
			var action='jy_weishop/goods.detail/getcomments/';
		}else{
			var action='jy_weishop/store.goodslist/list/';
		}
		app.util.get(action+query,function(res){
			//console.log('goods');console.log(res);
			if(res=='none'){
				the.setData({
					isnodata:true,
					'pagedata.goodslist':pagedata.goodslist,
					'pagedata.list':pagedata.list,
					'pagedata.params':pagedata.params,
					loading:false,
				});
			}else{
				if(pagedata.showlist=='pingjia'){
					pagedata.list = pagedata.list.concat(res.list)
				}else{
					pagedata.goodslist = pagedata.goodslist.concat(res)
				}
				if(pagedata.params.page==1){
					pagedata.oldlist[pagedata.nowckey]=res
					the.setData({
						'pagedata.oldlist':pagedata.oldlist,
					});
				}
				pagedata.params.page++
				the.setData({
					'pagedata.list':pagedata.list,
					'pagedata.goodslist':pagedata.goodslist,
					'pagedata.params':pagedata.params,
					isnodata:isnodata,
					loading:false,
				});
				
			}
		});
	},
	selectcategory:function(e){
		var the=this;
		var pagedata=the.data.pagedata
		var data=e.currentTarget.dataset;
		if(data.index!='all'){
			pagedata.params.pcate=pagedata.category[data.index].id;
		}else{
			pagedata.params.pcate='all';
		}
		the.setData({
			'pagedata.nowckey':data.index,
			'pagedata.params':pagedata.params,
			'pagedata.goodslist':pagedata.oldlist[data.index],
			isnodata:false
		})
    setTimeout(()=>{the.get_list(1);},100);
	},
	uptype:function(e){
		var the=this;
		var data=e.currentTarget.dataset;
		var pagedata=the.data.pagedata;
		the.setData({
			'pagedata.params.type':data.type
		})
	},
	showcarts:function(e){
		var the=this;
		var data=e.currentTarget.dataset;
		var pagedata=the.data.pagedata;
		the.setData({
			'pagedata.showcarts':data.type
		})
	},
	selecttaocan:function(e){
		var the=this;
		var pagedata=the.data.pagedata;
		var data=e.currentTarget.dataset;
		pagedata.g=pagedata.goodslist[data.gkey];
		pagedata.nowgkey=data.gkey
		the.setData({
			'pagedata.g':pagedata.g,
			'pagedata.nowgkey':pagedata.nowgkey,
			selecttaocan:true
		})
	},
	closetaocan:function(){
		var the=this;
		the.setData({
			selecttaocan:false
		})
	},
	showlist:function(e){
		var the=this;
		var data=e.currentTarget.dataset;
		var pagedata=the.data.pagedata;
		the.setData({
			'pagedata.showlist':data.showlist
		})
		if(data.showlist=='goods' || data.showlist=='pingjia'){
			setTimeout(()=>{the.get_list(1);},500);
		}
	},
	//减少
	minus:function(e){
		var the=this;
		var pagedata=the.data.pagedata
		var data=e.currentTarget.dataset;
		if(data.iscart){
			var g=data.g
			var carttotal=g.total
			var cartid=g.id
			var goodsid=g.goodsid
		}else{
			var g=pagedata.goodslist[data.gkey];
			var cartid=g.cartid
			var goodsid=g.id;
			var carttotal=g.carttotal;
		}
		if(carttotal<=0){
			return false;
		}
		app.util.showLoading('减少中...');
		app.util.post('jy_weishop/member.cart/minus/',{'storeid':pagedata.store.id,'getlist':true,'id':cartid},function(res){
				app.util.hideLoading();
				if(res=='success'){
					return false;
				}
				if(data.iscart){
					g.total--
					for (var j = 0; j < pagedata.goodslist.length; j++) {
							if(pagedata.goodslist[j].id==goodsid){
								pagedata.goodslist[j].carttotal=g.total
								if(g.optionid>0 && pagedata.goodslist[j].post){
									pagedata.goodslist[j].post[g.optionid].num--
								}
							}
							
					}
				}else{
					pagedata.goodslist[data.gkey]=g;
				}
				for (var i = 0; i < pagedata.category.length; i++) {
						if(pagedata.category[i].id==g.pcate){
							pagedata.category[i].total--
						}
					}
				if(res!='success'){
					g.carttotal--;
					pagedata.carts=res.list				
					pagedata.allnum--
					pagedata.totalprice-=g.price*1
				}
				the.setData({
					'pagedata.category':pagedata.category,
					'pagedata.g':g,
					'pagedata.goodslist':pagedata.goodslist,
					'pagedata.allnum':pagedata.allnum,
					'pagedata.totalprice':pagedata.totalprice,
					'pagedata.carts':pagedata.carts,
				})
				the.refresh(pagedata.totalprice);
				
		});
	},
//增加
    plus:function(e){
		var the=this;
		var pagedata=the.data.pagedata
		var data=e.currentTarget.dataset;
		if(data.iscart){
			var g=data.g
			var carttotal=g.total
			var goodsid=g.goodsid
			var cartid=g.id
			if(g.optionid>0){
				if(parseInt(carttotal)>=parseInt(g.options.stock)){
					app.util.message('不能再添加了，已超过库存！','error');
					return false;
				}
			}else{
				if(parseInt(carttotal)>=parseInt(g.goodstotal)){
					app.util.message('不能再添加了，已超过库存！','error');
					return false;
				}
			}
		}else{
			var g=pagedata.goodslist[data.gkey];
			var cartid=g.cartid
			var goodsid=g.id;
			var carttotal=g.carttotal;
			g.optionid=0;
			if(parseInt(carttotal)>=parseInt(g.total)){
				app.util.message('不能再添加了，已超过库存！','error');
				return false;
			}
		}
		app.util.showLoading('加入中...');
		app.util.post('jy_weishop/member.cart/addtocart/',{'storeid':pagedata.store.id,'getlist':true,'goodsid':goodsid,'optionid':g.optionid},function(res){
				app.util.hideLoading();
				if(res=='success'){
					return false;
				}
				if(data.iscart){
					g.total++
					for (var j = 0; j < pagedata.goodslist.length; j++) {
							if(pagedata.goodslist[j].id==goodsid){
								pagedata.goodslist[j].carttotal=g.total
								if(g.optionid>0 && pagedata.goodslist[j].post){
									pagedata.goodslist[j].post[g.optionid].num++
								}
							}	
					}
				}else{
					pagedata.goodslist[data.gkey]=g;
					if(res.cartid>0){
						g.cartid=res.cartid;
					}
				}
				for (var i = 0; i < pagedata.category.length; i++) {
						if(pagedata.category[i].id==g.pcate){
							pagedata.category[i].total++
						}
				}
				if(res!='success'){
					g.carttotal++;
					pagedata.carts=res.list;
					pagedata.g=g;
					pagedata.allnum++
					pagedata.totalprice+=g.price*1
				}
				the.setData({
					'pagedata.category':pagedata.category,
					'pagedata.goodslist':pagedata.goodslist,
					'pagedata.allnum':pagedata.allnum,
					'pagedata.totalprice':pagedata.totalprice,
					'pagedata.carts':pagedata.carts,
				})
				the.refresh(pagedata.totalprice);
		});
	},
	//减少
	sp_minus:function(){
		var the=this;
		var pagedata=the.data.pagedata
		var g =pagedata.g;
		if(g.carttotal<=0){
			return false;
		}
		app.util.showLoading('减少中...');
		app.util.post('jy_weishop/member.cart/minus/',{'storeid':pagedata.store.id,'getlist':true,'id':g.cartid,'optionid':g.options.id},function(res){
				app.util.hideLoading();
				if(res=='success'){
					return false;
				}
				if(g.post[g.options.id].num<=0){
					return false;
				}
				g.carttotal--;
				pagedata.carts=res.list
				g.post[g.options.id].num--;
				for (var i = 0; i < pagedata.category.length; i++) {
						if(pagedata.category[i].id==g.pcate){
							pagedata.category[i].total--
						}
					}
				pagedata.goodslist[pagedata.nowgkey]=g
				pagedata.allnum--
				pagedata.totalprice-=g.options.price*1
				the.setData({
					'pagedata.category':pagedata.category,
					'pagedata.g':g,
					'pagedata.goodslist':pagedata.goodslist,
					'pagedata.allnum':pagedata.allnum,
					'pagedata.totalprice':pagedata.totalprice,
					'pagedata.carts':pagedata.carts,
				})
				the.refresh(pagedata.totalprice);
				
		});
	},
	//增加
	sp_plus:function(e){
		var the=this
		var pagedata=the.data.pagedata
		var g =pagedata.g;
		if(parseInt(g.carttotal)>=parseInt(g.options.stock)){
			app.util.message('不能再添加了，已超过库存！','error');
			return false;
		}
		app.util.showLoading('加入中...');
		app.util.post('jy_weishop/member.cart/addtocart/',{'storeid':pagedata.store.id,'getlist':true,'goodsid':g.id,'optionid':g.options.id},function(res){				
				app.util.hideLoading();
				if(res!='success'){
					if(res.cartid>0){
						g.cartid=res.cartid;
					}
					g.carttotal++;
					g.post[g.options.id].num++;
					pagedata.carts=res.list
					for (var i = 0; i < pagedata.category.length; i++) {
						if(pagedata.category[i].id==g.pcate){
							pagedata.category[i].total++
						}
					}
					pagedata.goodslist[pagedata.nowgkey]=g
					pagedata.allnum++
					pagedata.totalprice+=g.options.price*1
					console.log(pagedata.nowckey)
					the.setData({
						'pagedata.category':pagedata.category,
						'pagedata.g':g,
						'pagedata.goodslist':pagedata.goodslist,
						'pagedata.allnum':pagedata.allnum,
						'pagedata.totalprice':pagedata.totalprice,
						'pagedata.carts':pagedata.carts,
					})
					the.refresh(pagedata.totalprice);
				}
				
		});
	},
	//刷新总数和总价
    refresh:function(totalprice){
		var the=this;
		var showprice=app.util.price(totalprice);
		the.setData({
			'pagedata.showprice':showprice
		})
	},
	//选择
	get_optionsid:function(e){
		var the=this
		var pagedata=the.data.pagedata
		var specid = pagedata.g.specid;
		var data=e.currentTarget.dataset;
		pagedata.g.specid[data.index]=data.specid
		specid = specid.join('_');
		console.log(specid);
		app.util.post('jy_weishop/goods.detail/get_optionsid/',{'goodsid':pagedata.g.id,'specid':specid,'isdish':1},function(res){
				var optionsid=res.options.id;
				//console.log(res);
				pagedata.g.options=res.options;
				pagedata.g.selespename=res.selespename;
				if(res.cartid){
					pagedata.g.cartid=res.cartid;
				}
				if(!pagedata.g.post[optionsid]){
					pagedata.g.post[optionsid]={}
					pagedata.g.post[optionsid]={
						'num':pagedata.g.post[optionsid].num?pagedata.g.post[optionsid].num:res.carttotal,
						'title':res.selespename,
					}
				}
				
				the.setData({
					'pagedata.g':pagedata.g
				})
		});
	},
	info_login:function(e){
		//根据openid为用户登陆，此处尝试获取用户信息
		var the=this;
		app.util.getUserInfo(e,function(res){
			the.getpagedata();
		});
		the.setData({
			ShowAuthM:false
		})
	},
  	click:function(evt){
		//用户点击事件 data.func 为方法名，data.params 为调用参数！
		var data=evt.currentTarget.dataset;
		app.util[data.func](data.params);
	},
	click_tab:function(evt){
		//用户点击事件 data.func 为方法名，data.params 为调用参数！
		var data=evt.currentTarget.dataset;
		app.util.tab(data.params);
	},
	formSubmit:function(event){
		var data=event.detail.value;
		app.util.post('post',data);
	},
	keyword:function(){
		var the = this
		var pagedata = the.data.pagedata
		pagedata.keyword = e.detail.value
	},
	closegoodsdetail:function(){
		var the=this;
		the.setData({
			showgoodsdetail:false
		})
	},
	getgoodsdetail:function(e){
		var the=this
		var goodsid=e.currentTarget.dataset.id;
		var pagedata=the.data.pagedata
		the.setData({
			showgoodsdetail:true,
			loading:true,
			'pagedata.goods':{},
			'pagedata.goodsitem':{}
			
		})
		app.util.get('jy_weishop/goods.detail//id='+goodsid,function(res){
				//console.log(res)
				res.goods.content=res.goods.content.replace(/\<img/gi, '<img style="max-width:100%"' );
				pagedata.goodsitem=res;
				pagedata.showtype=0;
				pagedata.comments_type=pagedata.goodsitem.comments_type;
				pagedata.goods=res.goods;
				pagedata.comments=res.comments;
				pagedata.shopset=res.shopset;
				pagedata.commentsnum=res.commentsnum
				pagedata.commentsfen=res.commentsfen
				pagedata.goods.id=pagedata.goodsitem.goods.id;
				the.setData({
					'pagedata.goodsitem':pagedata.goodsitem,
					'pagedata.comments_type':pagedata.comments_type,
					'pagedata.goods':pagedata.goods,
					'pagedata.comments':pagedata.comments,
					'pagedata.shopset':pagedata.shopset,
					'pagedata.commentsnum':pagedata.commentsnum,
					'pagedata.commentsfen':pagedata.commentsfen,
					showtype:0,
					loading:false
				})
				the.getcomments(1);
			});
	},
	setlike:function(){
		var the=this
		var pagedata = the.data.pagedata
		pagedata.islike = !pagedata.islike;		
		the.setData({
				'pagedata.islike':pagedata.islike
		});
		app.util.get('jy_weishop/goods.detail/like/',function(){
			if(pagedata.islike){
				app.util.msg('关注成功');
			}else{
				app.util.msg('关注失败');
			}
		});
	},
	setvideo:function(e){
		var page=this
		var type = e.currentTarget.dataset.type;
		page.setData({
				'pagedata.goods.isvideo':type
		});
	},
	showtype:function(e){
		var page=this
		var pagedata = this.data.pagedata
		page.setData({
				showtype:e.currentTarget.dataset.showtype
		});
	},
	getcomments:function(e){
		var the=this;
		var page = the.data.page
		var pagedata=the.data.pagedata
		var isnodata = the.data.isnodata
		pagedata.commentsparams = pagedata.commentsparams?pagedata.commentsparams:{}
		if(e){
			if(e.currentTarget){
				var data=e.currentTarget.dataset;
				if(data.type){
					pagedata.commentsparams.type=data.type;
					pagedata.comments_type=data.type;
					the.setData({
						'pagedata.comments_type':data.type
					});
				}
			}
			page = 1;
			pagedata.comments=[];
			isnodata=false;
		}else{
			if(isnodata){
				return false;
			}
		}
		var query='page='+page;
		var more_query=app.util.made_query(pagedata.commentsparams);
		if(more_query){
			query+='&'+more_query;
		}
		console.log('query');console.log(query);
		app.util.get('jy_weishop/goods.detail/getcomments/'+query,function(res){
			//console.log('getcomments');console.log(res);
			if(res=='none'){
				the.setData({
					isnodata:true,
					'pagedata.comments':pagedata.comments,
					loading:false,
				});
			}else{
				pagedata.comments = pagedata.comments.concat(res.list)
				page++
				the.setData({
					'pagedata.comments':pagedata.comments,
					page:page,
					isnodata:isnodata,
					loading:false,
				});
			}
			
		});
	},
	commentsshowtype:function(){
		var the=this
		the.setData({
				showtype:3
		});
	},
	show_bigimage:function(e){
		var the=this
		var img=e.currentTarget.dataset.img;
		the.setData({
			'pagedata.show_bigimage':!the.data.pagedata.show_bigimage,
			'pagedata.showimage':img
		});
	},
	openLocation:function(e){
		var the=this
		var data=e.currentTarget.dataset;
		var pagedata = the.data.pagedata
		qqmapsdk = new QQMapWX({
			key: pagedata.qqmap_ak?pagedata.qqmap_ak:'SN2BZ-MKT32-22SU7-COVX6-ZYXAQ-OEF6D'
		});
		qqmapsdk.geocoder({
          address: data.address,
          success: res => {
              wx.openLocation({
                  latitude: res.result.location.lat,
                  longitude: res.result.location.lng,
                  scale: 28
              })
          },
          fail: function(res) {
              console.log(res);
          },
          complete: function(res) {
              console.log(res);
          }
		});
	},
	call:function(e){
		var phoneNumber = e.currentTarget.dataset.phone;
		wx.makePhoneCall({
		  phoneNumber: phoneNumber
		})
	},
	setlike:function(e){
		var the=this
		var data=e.currentTarget.dataset;
		var pagedata=the.data.pagedata
		app.util.post('jy_weishop/store.goodslist/like/',data,function(res){
			app.util.msg(res);
			pagedata.store.islike=pagedata.store.islike==1?0:1;
			the.setData({
				'pagedata.store':pagedata.store
			})
		});
	},
	check_buy:function(){
		var the=this
		var pagedata = this.data.pagedata
		app.util.get('jy_weishop/store.goodslist/check_buy/isresurl=1&storeid='+pagedata.store.id+'&tableid='+pagedata.tableid,function(resurl){
			app.util.access(resurl);
		});
	},
	goback: function() {
		var pages=getCurrentPages()
		if(pages.length>1){
			wx.navigateBack({
				'delta':1,
				'fail':function(){
					//console.log('333');
					app.util.access(app.plugin_name+'/index/');
				},
			})
		}else{
			app.util.access(app.plugin_name+'/index/');
		}
    },
	addtocartall:function(e){
		var the =this
		var pagedata =the.data.pagedata
		var data=e.currentTarget.dataset;
		app.util.post('jy_weishop/goods.detail/addtocart/',{'goodsid':data.goodsid},function(res){
				if(app.session.menus && app.session.menus.length>0){	
					for(var i=0;i<app.session.menus.length;i++){
						if(app.session.menus[i].action=='jy_weishop/member.cart/'){
							app.session.menus[i].badge++
							the.setData({
								pluginnav:app.session.menus,
							})
						}
					}
				}
				app.util.msg('添加成功');
		});
	},
	onShareAppMessage: function (res) {
		var the = this
		var pagedata = the.data.pagedata
		if (res.from === 'button') {
		}
		var path=the.data.route+'?'+app.access.query+'&id='+pagedata.store.id;
		if(app.access.op){
			path +='&op='+app.access.op;
		}
		if(pagedata.fromuser){
			path +='&fromuser='+pagedata.fromuser;
		}
		return {
		  title: the.data.pagetitle,
		  path: path,
		  desc: app.setting.sharedesc,
		  success: function(res) {
		  },
		  fail: function(res) {
		  }
		}
	},
	onShareTimeline: function (res) {
		var the = this
		var pagedata = the.data.pagedata
		var query=app.access.query
		if(app.access.op){
			query +='&op='+app.access.op;
		}
		if(pagedata.fromuser){
			query +='&fromuser='+pagedata.fromuser;
		}
		query +='&isgoshare=1'
		return {
		  title: the.data.pagetitle,
		  query: query,
		  desc: app.setting.sharedesc,
		  success: function(res) {
		  },
		  fail: function(res) {
		  }
		}
	},
});